import React, { useState, useEffect, useRef } from 'react';
import { Card, Form, Input, Button, Checkbox, message, Typography } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import '../css/LoginPage.css';
import { useNavigate } from 'react-router-dom';
import { Modal } from 'antd';
import { api } from '../api/api';
import Url from '../api/url';

const { Title } = Typography;

const ParticleEffect = () => {
  const canvasRef = useRef(null);
  const particlesRef = useRef([]);
  const mouseRef = useRef({ x: 0, y: 0 });
  const [windowSize, setWindowSize] = useState({ width: window.innerWidth, height: window.innerHeight });

  useEffect(() => {
    const canvas = canvasRef.current;
    const ctx = canvas.getContext('2d');
    let animationFrameId;

    const createParticle = (x, y) => ({
      x,
      y,
      size: Math.random() * 2 + 0.5,
      speedX: Math.random() * 1 - 0.5,
      speedY: Math.random() * 1 - 0.5,
      life: 1,
      color: Math.random() > 0.5 ? '255,255,255' : '200,230,255'  // 调整为白色和浅蓝色
    });

    const initParticles = () => {
      for (let i = 0; i < 50; i++) {
        particlesRef.current.push(
          createParticle(
            Math.random() * windowSize.width,
            Math.random() * windowSize.height
          )
        );
      }
    };

    const handleResize = () => {
      setWindowSize({
        width: window.innerWidth,
        height: window.innerHeight,
      });
      canvas.width = window.innerWidth;
      canvas.height = window.innerHeight;
    };

    const handleMouseMove = (e) => {
      mouseRef.current = {
        x: e.clientX,
        y: e.clientY
      };
      // 鼠标移动时添加新粒子
      for (let i = 0; i < 2; i++) {
        particlesRef.current.push(createParticle(e.clientX, e.clientY));
      }
    };

    const animate = () => {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      
      particlesRef.current.forEach((particle) => {
        particle.life -= 0.01;
        particle.x += particle.speedX;
        particle.y += particle.speedY;

        // 计算与鼠标的距离，实现跟随效果
        const dx = mouseRef.current.x - particle.x;
        const dy = mouseRef.current.y - particle.y;
        const distance = Math.sqrt(dx * dx + dy * dy);

        if (distance < 100) {
          const force = (100 - distance) / 100;
          particle.speedX += (dx / distance) * force * 0.1;
          particle.speedY += (dy / distance) * force * 0.1;
        }

        // 绘制粒子
        ctx.beginPath();
        ctx.arc(particle.x, particle.y, particle.size, 0, Math.PI * 2);
        ctx.fillStyle = `rgba(${particle.color}, ${particle.life * 0.6})`;
        ctx.fill();

        // 添加柔和的发光效果
        ctx.beginPath();
        ctx.arc(particle.x, particle.y, particle.size * 1.5, 0, Math.PI * 2);
        ctx.fillStyle = `rgba(${particle.color}, ${particle.life * 0.2})`;
        ctx.fill();
      });

      // 移除消失的粒子并添加新粒子
      particlesRef.current = particlesRef.current.filter(
        particle => particle.life > 0
      );

      if (particlesRef.current.length < 50) {
        particlesRef.current.push(
          createParticle(
            Math.random() * windowSize.width,
            Math.random() * windowSize.height
          )
        );
      }

      animationFrameId = requestAnimationFrame(animate);
    };

    canvas.width = windowSize.width;
    canvas.height = windowSize.height;
    initParticles();

    window.addEventListener('resize', handleResize);
    window.addEventListener('mousemove', handleMouseMove);
    animate();

    return () => {
      window.removeEventListener('resize', handleResize);
      window.removeEventListener('mousemove', handleMouseMove);
      cancelAnimationFrame(animationFrameId);
    };
  }, [windowSize]);

  return <canvas ref={canvasRef} className="particle-canvas" />;
};

const LoginPage = () => {
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const navigate = useNavigate();

   // 添加登录状态检查
  // useEffect(() => {
  //   const token = localStorage.getItem('token');
  //   if (token) {
  //     navigate('/');
  //   }
  // }, [navigate]);

  const onFinish = async (values) => {
    setLoading(true);
    try {
      // TODO: 这里添加实际的登录逻辑
      const res = await api({url:Url.login,data:values})
      const token = res.data.token
      const user = res.data.user
      localStorage.setItem('token', token); 
      localStorage.setItem('user', JSON.stringify(user)); 
      message.success(res.msg);
      navigate('/')
      // 登录成功后的跳转逻辑
    } catch (error) {
      if(error != "用户名或密码错误"){
        message.error('网络错误:'+error.message)
      }
    } finally {
      setLoading(false);
    }
  };

  const forgetPwd = () => {
      Modal.info({ title: '提示', content: '请联系管理员重置密码' });
  }

  return (
    <div className="login-container">
      <ParticleEffect />
      <div className="stars-container">
        <div className="star"></div>
        {/* <div className="star"></div>
        <div className="star"></div>
        <div className="star"></div>
        <div className="star"></div>
        <div className="star"></div>
        <div className="star"></div>
        <div className="star"></div> */}
      </div>
      <div className="aurora-container">
        <div className="aurora"></div>
        {/* <div className="aurora"></div>
        <div className="aurora"></div> */}
      </div>
      <Card className="login-card">
        <div className="login-header">
          <Title level={2} className="login-title">系统登录</Title>
          <p className="login-subtitle">欢迎回来，请输入您的账号密码</p>
        </div>
        <Form
          form={form}
          name="login"
          onFinish={onFinish}
          initialValues={{ remember: true }}
          className="login-form"
          clearOnDestroy
        >
          <Form.Item
            name="userId"
            rules={[{ required: true, message: '请输入用户名！' }]}
          >
            <Input
              prefix={<UserOutlined className="input-icon" />}
              placeholder="用户名"
              size="large"
              className="login-input"
            />
          </Form.Item>
          <Form.Item
            name="password"
            rules={[{ required: true, message: '请输入密码！' }]}
          >
            <Input.Password
              prefix={<LockOutlined className="input-icon" />}
              placeholder="密码"
              size="large"
              className="login-input"
            />
          </Form.Item>
          <Form.Item className="login-options">
            <Form.Item name="remember" valuePropName="checked" noStyle>
              <Checkbox className="remember-checkbox">记住密码</Checkbox>
            </Form.Item>
            <a className="login-form-forgot" href="#" onClick={forgetPwd}>
              忘记密码？
            </a>
          </Form.Item>
          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              className="login-button"
              loading={loading}
              size="large"
              block
            >
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>

      



    </div>
  );
};

export default LoginPage;